package cn.shengchao.wecom.schedule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.examstar.rpc.wecom.api.WeComSyncToLocalApi;
import cn.shengchao.examstar.rpc.wecom.dto.WeComCpUserDto;
import cn.shengchao.wecom.utils.WeComExternalContactHelper;
import cn.shengchao.wecom.utils.WeComTlxHelper;
import cn.shengchao.wecom.wxcp.acl.ports.repositories.ICpUserRepository;
import cn.shengchao.wecom.wxcp.infrastructure.dao.CpUserDao;
import cn.shengchao.wecom.wxcp.infrastructure.dao.CpUserQrcodeDao;
import cn.shengchao.wecom.wxcp.infrastructure.dao.po.CpUser;
import cn.shengchao.wecom.wxcp.infrastructure.dao.po.CpUserQrcode;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
import me.chanjar.weixin.cp.bean.user.WxCpDeptUserResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: examstarapi
 * @description: 通讯录同步组件
 * @author: Xiong weiqiang
 * @create: 2025-04-10 11:00
 */
@Component
public class WeComTlxSync {
    @Autowired
    private WeComTlxHelper weComTlxHelper;
    @DubboReference
    private WeComSyncToLocalApi weComSyncToLocalApi;
    @Autowired
    private ICpUserRepository cpUserRepository;
    @Autowired
    private CpUserDao cpUserDao;
    @Autowired
    private CpUserQrcodeDao cpUserQrcodeDao;

    @Autowired
    private WeComExternalContactHelper weComExternalContactHelper;
    private static final String DEFAULT_RULE_GROUP_STATE="RG0@0";
    /**
     * 同步企微上所有的成员到数据库
     */
    public void syncTlx(){
        try {
            //null开始
            syncDepartUser(null,-1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 同步通讯录的用户
     * @param currentCursor
     */
    private void syncDepartUser(String currentCursor,int index) throws WxErrorException {
        if (index==-1){
            index=0;
        }
        WxCpDeptUserResult result=weComTlxHelper.getWeComUserList(0,currentCursor,10);
        if (result.success()){
            String nextCursor=result.getNextCursor();
            List<WxCpDeptUserResult.DeptUserList> deptUserLists= result.getDeptUser();
            //如果部门用户不为空
            if (CollUtil.isNotEmpty(deptUserLists)){
                index+=deptUserLists.size();
//                List<WeComDeptUserDto> deptUserDtoList= BeanUtil.copyToList(deptUserLists, WeComDeptUserDto.class);
//                weComSyncToLocalApi.syncDeptUserList(deptUserDtoList);
                cpUserRepository.checkSave(deptUserLists);
            }
            //null结束
            if (StrUtil.isNotBlank(nextCursor)){
                //递归查所有用户
                syncDepartUser(nextCursor,index);
            }else {
                System.out.println("查询结束。。。。，企微号查询条数："+index);
            }
        }
    }
    public void checkUpdateCpUser(WeComCpUserDto weComCpUserDto){
        if (weComCpUserDto!=null&&weComCpUserDto.getUserId()!=null){
            CpUser cpUser=cpUserDao.selectOne(Wrappers.lambdaQuery(CpUser.class).eq(CpUser::getUserId,weComCpUserDto.getUserId()));
            if (cpUser!=null){
                //如果是换了id
                if (StrUtil.isNotBlank(weComCpUserDto.getNewUserId())){
                    cpUserDao.update(Wrappers.lambdaUpdate(CpUser.class).set(CpUser::getStatus,2).eq(CpUser::getUserId,weComCpUserDto.getUserId()));
                    cpUser=new CpUser();
                    cpUser.setUserId(weComCpUserDto.getNewUserId());
                }
                cpUser.setName(weComCpUserDto.getName());
                cpUser.setDepartment(Arrays.toString(weComCpUserDto.getDepartIds()));
                cpUser.setAlias(weComCpUserDto.getAlias());
                cpUser.setMainDepartment(weComCpUserDto.getMainDepartment());
                cpUser.setEmail(weComCpUserDto.getEmail());
                cpUser.setAddress(weComCpUserDto.getAddress());
                cpUser.setAvatar(weComCpUserDto.getAvatar());
                cpUser.setBizEmail(weComCpUserDto.getBizMail());
                cpUser.setThumbAvatar(weComCpUserDto.getThumbAvatar());
                cpUser.setTelephone(weComCpUserDto.getTelephone());
                cpUser.setPosition(weComCpUserDto.getPosition());
                cpUser.setStatus(weComCpUserDto.getStatus());
                cpUser.setDirectLeader(Arrays.toString(weComCpUserDto.getDirectLeader()));
                cpUser.setLoadStatus(1);
                cpUser.setOpenUserId(weComCpUserDto.getOpenUserId());
                cpUser.setIsLeaderInDept(Arrays.toString(weComCpUserDto.getIsLeaderInDept()));
                cpUser.setLastUpdateTime(new Date());
                if (cpUser.getId()!=null){
                    cpUserDao.updateById(cpUser);
                }else {
                    cpUserDao.insert(cpUser);
                }
            }
        }
    }
    @Transactional
    public void checkContactMeQrcode(List<String> userIds) {
        List<CpUser> userList=cpUserDao.selectList(Wrappers.lambdaQuery(CpUser.class).in(CpUser::getUserId,userIds));
        System.out.println("正在检查企微成员二维码："+ JSONUtil.toJsonStr(userIds));
        Map<String,CpUser> cpUserMap=userList.stream().collect(Collectors.toMap(CpUser::getUserId, Function.identity(),(v1, v2)->v2));
        for (String userId:userIds){
            WxCpContactWayInfo.ContactWay contactWay=new WxCpContactWayInfo.ContactWay();
            contactWay.setUsers(CollUtil.newArrayList(userId));
            contactWay.setState(DEFAULT_RULE_GROUP_STATE);
            contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
            contactWay.setType(WxCpContactWayInfo.TYPE.SINGLE);
            contactWay.setRemark("");
            WxCpContactWayResult result= null;
            try {
                result = weComExternalContactHelper.getContactMe(contactWay);
                if (result.success()){
                    CpUser cpUser=cpUserMap.get(userId);
                    cpUser.setQrCodeStatus(1);
                    cpUser.setQrCodeUrl(result.getQrCode());
                    cpUser.setLastUpdateTime(new Date());
                    cpUserDao.updateById(cpUser);
                    CpUserQrcode cpUserQrcode=new CpUserQrcode();
                    cpUserQrcode.setUser(userId);
                    cpUserQrcode.setConfigId(result.getConfigId());
                    cpUserQrcode.setQrCode(result.getQrCode());
                    cpUserQrcode.setParty("");
                    cpUserQrcode.setType("1");
                    cpUserQrcode.setGenTime(new Date());
                    cpUserQrcode.setLastLoadTime(new Date());
                    cpUserQrcode.setScene("2");
                    cpUserQrcode.setState(DEFAULT_RULE_GROUP_STATE);
                    cpUserQrcodeDao.insert(cpUserQrcode);
                }
            } catch (WxErrorException e) {
                System.out.println("获取二维码失败："+ ExceptionUtil.getRootCauseMessage(e));
                CpUser cpUser=cpUserMap.get(userId);
                cpUser.setQrCodeStatus(0);
                cpUser.setQrCodeError(e.getMessage());
                cpUser.setLastUpdateTime(new Date());
                cpUserDao.updateById(cpUser);
            }
        }
    }
}